<template>
  <el-form :model="form" :rules="rules" ref="formRef">
    <el-form-item label="广告位" prop="type" :label-width="formLabelWidth">
      <el-select v-model="form.type" style="width:100%" placeholder="请选择" @change="selectClick">
        <el-option
          v-for="item in productOptions"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="广告标题" prop="name" :label-width="formLabelWidth">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="序号" prop="sort" :label-width="formLabelWidth">
      <el-input-number v-model="form.sort" :min="0" :precision="0" :step="1" :controls="false"></el-input-number>
      <!-- <el-input v-model.number="form.sort"></el-input> -->
    </el-form-item>
    <el-form-item label="广告绑定" prop="isDefault" :label-width="formLabelWidth">
      <el-radio-group v-model="form.isDefault" @change="changeEvent">
        <el-radio
          label="0"
          v-if="form.type =='1'||form.type =='5'||form.type =='6'||form.type =='7'||form.type =='8'||form.type =='9'"
        >不绑定</el-radio>
        <el-radio
          label="1"
          v-if="form.type =='1'||form.type =='2'||form.type =='3'||form.type =='4'||form.type =='5'"
        >绑定商品</el-radio>
        <el-radio label="2" v-if="form.type =='5'">绑定链接</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="商品" prop="spuId" :label-width="formLabelWidth" v-if="show">
      <el-cascader
        v-model="form.spuId"
        :props="props"
        :show-all-levels="false"
        :options="options"
        placeholder="请选择绑定商品"
      ></el-cascader>
      <!-- <el-select v-model="form.spuId" placeholder="请选择绑定商品">
        <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"></el-option>
      </el-select>-->
    </el-form-item>
    <el-form-item label="链接" prop="href" :label-width="formLabelWidth" v-if="form.isDefault =='2'">
      <el-input v-model="form.href"></el-input>
    </el-form-item>
    <el-form-item label="上传图片" prop="url" :label-width="formLabelWidth">
      <el-checkbox-group v-model="form.url" v-show="false"></el-checkbox-group>
      <el-upload
        class="avatar-uploader"
        action
        :http-request="upload"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="form.url" :src="form.url" class="avatar" />
        <i v-else style="line-height: 100px;" class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <span style="color:red" v-if="form.type =='1'">图片尺寸限制为346 x 346</span>
      <span style="color:red" v-if="form.type =='5'">图片尺寸限制为320 x 240</span>
      <span style="color:red" v-if="form.type =='6'">图片尺寸限制为334 x 172</span>
      <span style="color:red" v-if="form.type =='7'">图片尺寸限制为334 x 108</span>
      <span style="color:red" v-if="form.type =='8'">图片尺寸限制为334 x 108</span>
      <el-dialog :visible.sync="dialogVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt />
      </el-dialog>
    </el-form-item>
    <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
      <el-input type="textarea" :rows="3" v-model="form.remark"></el-input>
    </el-form-item>
    <el-form-item :label-width="formLabelWidth">
      <el-button plain @click="resetForm('formRef')">取消</el-button>
      <el-button type="primary" @click="submitForm('formRef')">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    var validate = (rule, value, callback) => {
      if (this.form.isDefault == "1") {
        if (value === "") {
          callback(new Error("请绑定商品"));
        }
      } else if (this.form.isDefault == "2") {
        if (value === "") {
          callback(new Error("请填写链接"));
        }
      }
      callback();
    };

    return {
      productOptions: [
        { id: "1", title: "首页banner广告位" },
        { id: "2", title: "首页推广位" },
        { id: "3", title: "订单支付完成后页面广告位" },
        { id: "4", title: "我的页面底部广告位" },
        { id: "5", title: "开屏弹窗广告位" },
        { id: "6", title: "秒杀广告位" },
        { id: "7", title: "拼团广告位" },
        { id: "8", title: "打包一口价广告位" }
        // { id: "9", title: "优惠券广告" }
      ],
      form: {
        name: "",
        url: "",
        spuId: "",
        isDefault: "0",
        sort: "",
        type: "",
        href: "",
        bannertype: "0",
        compel: "0",
        remark: ""
      },
      options: [],
      formLabelWidth: "120px",
      dialogVisible: false,
      dialogImageUrl: "",
      rules: {
        type: [{ required: true, message: "请选择广告位", trigger: "change" }],
        name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
        sort: [
          { required: true, message: "请输入序号", trigger: "blur" },
          { type: "number", message: "序号必须为数字值", trigger: "blur" }
        ],
        spuId: [{ required: true, validator: validate, trigger: "blur" }],
        url: [{ required: true, message: "请选择图片", trigger: "change" }],
        href: [{ required: true, validator: validate, trigger: "blur" }],
        remark: [{ required: true, message: "请填写备注", trigger: "blur" }]
      },
      show: false,
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          const { value, level } = node;

          if (level == 0) {
            const nodes = this.options.map(item => ({
              value: item.label,
              label: item.value,
              leaf: level >= 1
            }));

            this.$service.firstGoods().then(res => {
              console.log(res);
              let list = res.data;
              // this.options = res;
              let arr = [];
              list.forEach(item => {
                arr.push({
                  value: item.id,
                  label: item.name,

                  leaf: level >= 2
                });
              });
              resolve(arr);
              // console.log(res.obj);
            });
          } else if (level == 1) {
            this.$service.secondGoods(node.value).then(res => {
              const nodes = res.data.map(item => {
                return {
                  value: item.id,
                  label: item.name,
                  leaf: level >= 2
                };
              });
              resolve(nodes);
            });
          } else if (level == 2) {
            var param = {
              tbSpu: {
                cid2: node.value
              }
            };
            this.$service.getCommodityCategory(param).then(res => {
              const nodes = res.data.map(item => {
                return {
                  value: item.id,
                  label: item.title,
                  leaf: level >= 2
                };
              });
              resolve(nodes);
            });
          }
          // else if (level == 3) {
          //   this.$service.getSkus(node.value).then(res => {
          //     const nodes = res.data.map(item => {
          //       return {
          //         value: item.id,
          //         label: item.title,
          //         leaf: level >= 3
          //       };
          //     });
          //     resolve(nodes);
          //   });
          // }
          else {
            resolve([]);
          }
        }
      }
    };
  },
  mounted() {
    // this.$service.getAllspu().then(res => {
    //   //console.log(res);
    //   this.options = res.data;
    // });
  },
  methods: {
    // 图片上传之前
    beforeAvatarUpload(file) {
      var scale = "";
      // imgSize.js
      //  图片尺寸限制
      var self =this;
      if (this.form.type == "1") {
        scale = 346 / 346;
        const isSize = this.Global.imgSize(file,scale,self,"上传的图片建议比例346:346"); // 这里使用,传入file值
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error("上传图片大小不得超过2MB!");
        // }
        console.log(isSize)
        if (!isSize) {
           this.$message({
            message: "上传的图片建议比例346:346",
            type: "warning"
          });
        }
        //  校验不通过则不上传文件
        return isSize;
      } else if (this.form.type == "5") {
        scale = 320 / 240;
        const isSize = this.Global.imgSize(file,scale,self,"上传的图片建议比例320:240"); // 这里使用,传入file值
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error("上传图片大小不得超过2MB!");
        // }
        if (!isSize) {
          this.$message({
            message:"上传的图片建议比例320:240",
            type: "warning"
          });
        }
        //  校验不通过则不上传文件
        return isSize;
      } else if (this.form.type == "6") {
        scale = 334 / 172;
        const isSize = this.Global.imgSize(file,scale,self,"上传的图片建议比例334:172"); // 这里使用,传入file值
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error("上传图片大小不得超过2MB!");
        // }
        if (!isSize) {
          this.$message({
            message:"上传的图片建议比例334:172",
            type: "warning"
          });
        }
        //  校验不通过则不上传文件
        return isSize;
      } else if (this.form.type == "7") {
        scale = 334 / 108;
        const isSize = this.Global.imgSize(file,scale,self,"上传的图片建议比例334:108"); // 这里使用,传入file值
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error("上传图片大小不得超过2MB!");
        // }
        if (!isSize) {
          this.$message({
            message:"上传的图片建议比例334:108",
            type: "warning"
          });
        }
        //  校验不通过则不上传文件
        return isSize;
      } else if (this.form.type == "8") {
        scale = 334 / 108;
        const isSize = this.Global.imgSize(file,scale,self,"上传的图片建议比例334:108");; // 这里使用,传入file值
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error("上传图片大小不得超过2MB!");
        // }
        if (!isSize) {
            this.$message({
            message:"上传的图片建议比例334:108",
            type: "warning"
          });
        }
        //  校验不通过则不上传文件
        return isSize;
      }
    },
    selectClick(e) {
      if (e == "2" || e == "3" || e == "4") {
        this.form.isDefault = "1";
        this.show = true;
      } else {
        this.form.isDefault = "0";
        this.show = false;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        console.log(111, valid);
        if (valid) {
          var spuID = "";
          if (this.form.spuId.length > 0) {
            spuID = this.form.spuId[2];
          }
          var form = {
            name: this.form.name,
            url: this.form.url,
            spuId: spuID,
            isDefault: this.form.isDefault,
            sort: this.form.sort,
            type: this.form.type,
            href: this.form.href,
            bannertype: this.form.bannertype,
            compel: this.form.compel,
            remark: this.form.remark
          };
          this.$service.tbBannerInsert(form).then(res => {
            if (res.code == "00000") {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.$refs[formName].resetFields();
              this.$emit("submit", false);
            } else {
              this.$message({
                message: res.message,
                type: "warning"
              });
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.$emit("submit", false);
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, file) {
      console.log(111, res, file);
      this.form.imageUrl = URL.createObjectURL(file.raw);
    },
    changeEvent(e) {
      if (e == 1) {
        this.show = true;
      } else {
        this.show = false;
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    upload(file) {
      this.$service.uploadFileFunction(file, result => {
        //console.log(result);
        this.form.url = result.url;
      });
    }
  }
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>